<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="cate_ids">
              <el-cascader clearable placeholder="请选择分类" v-model="searchForm.cate_ids" :props="{ value: 'id',label:'name',children:'children'}"
                :options="seachrCateInfo" @change="handleChange">
              </el-cascader>
            </el-form-item>
            <el-form-item prop="name">
              <el-input placeholder="请输入商品名" v-model="searchForm.name" clearable>
              </el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="上架" value="1"></el-option>
                <el-option label="下架" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="unit_type">
              <el-select v-model="searchForm.unit_type" clearable placeholder="请选择是否过称">
                <el-option label="过称" value="1"></el-option>
                <el-option label="不过称" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="is_activity">
              <el-select v-model="searchForm.is_activity" clearable placeholder="请选择是否活动中">
                <el-option label="非活动中" value="0"></el-option>
                <el-option label="活动中" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search(true)">搜索</el-button>
              <el-button type="success" @click.stop="refresh">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="table" border>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="简介:">
                  <span>{{ props.row.info }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="cate_name" label="所属分类"></el-table-column>
          <el-table-column prop="center_name" label="所属中心"></el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.image" :fit="fit" :preview-src-list="[scope.row.image]"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="pur_price" label="最新采购价"></el-table-column>
          <el-table-column prop="price" label="授信价"></el-table-column>
          <el-table-column prop="price_percent" label="授信百分比"></el-table-column>
          <el-table-column prop="ot_price" label="非授信价"></el-table-column>
          <el-table-column prop="ot_price_percent" label="非授信百分比"></el-table-column>
          <el-table-column prop="act_price" label="活动价"></el-table-column>
          <el-table-column label="活动">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.is_activity == 1 ?'活动中': '非活动中'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.is_activity" :active-value="1" active-color="#E6A23C" :inactive-value="0"
                  @change="changeIsStatus(scope.row,'is_activity')">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序"></el-table-column>
          <el-table-column prop="stock" label="非冻结库存" width="100"></el-table-column>
          <el-table-column prop="ice_stock" label="冻结库存"></el-table-column>
          <el-table-column prop="sales" label="销量"></el-table-column>
          <el-table-column prop="unit_name" label="单位"></el-table-column>
          <el-table-column prop="unit_type" label="是否过称">
            <template slot-scope="scope">
              {{unitTypeName(scope.row.unit_type)}}
            </template>
          </el-table-column>
          <el-table-column prop="center_name" label="所属中心"></el-table-column>
          <el-table-column label="新品">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.is_new == 1 ?'新品': '非新品'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.is_new" :active-value="1" active-color="#67C23A" :inactive-value="0"
                  @change="changeIsStatus(scope.row,'is_new')">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="热卖">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.is_hot == 1 ?'热卖': '非热卖'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.is_hot" :active-value="1" active-color="#E6A23C" :inactive-value="0"
                  @change="changeIsStatus(scope.row,'is_hot')">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="优品推荐">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.is_good == 1 ?'优品推荐': '非优品推荐'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.is_good" :active-value="1" active-color="#F56C6C" :inactive-value="0"
                  @change="changeIsStatus(scope.row,'is_good')">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.status == 1 ?'上架': '下架'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-dropdown trigger="click" @command="handleCommand">
                <el-button type="primary">
                  操作菜单<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{cmd:'edit', id:scope.row.id}">编辑数据</el-dropdown-item>
                  <el-dropdown-item :command="{cmd:'del', id:scope.row.id}">删除数据</el-dropdown-item>
                  <el-dropdown-item :command="{cmd:'description', id:scope.row.id}">商品详情</el-dropdown-item>
                  <el-dropdown-item :command="{cmd:'showLog', id:scope.row.id}">查看记录</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="(val) =>{return handleSizeChange(val,'searchForm', 'search')}"
            @current-change="(val) =>{return handleCurrentChange(val,'searchForm', 'search')}" :current-page="searchForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑商品" :visible.sync="editVisible" :before-close="handleClose('editForm')" width="800px">
        <el-form ref="editForm" :model="editForm" label-width="180px" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类" prop="cate_path">
                <el-cascader clearable ref="addCascader" placeholder="请选择分类" v-model="editForm.cate_path"
                  :props="{ value: 'id',label:'name',children:'children' }" :options="cateInfo">
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="分拣中心" prop="center_id">
                <el-select v-model="editForm.center_id" placeholder="请选择分拣中心" clearable>
                  <el-option v-for="item in centerInfo" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="unit_id">
                <el-select v-model="editForm.unit_id" placeholder="请选择单位" clearable>
                  <el-option v-for="item in unitInfo" :key="item.id" :label="item.name + '---' +(item.type == 1 ? '过称' : '不过称')" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="图片" prop="image">
                <el-upload ref="editImage" name="image" action="#"
                  :on-change="(file, fileList) => {return handleImgChange(file, fileList, 'editForm', 'editImage')}"
                  :on-remove="(file, fileList) => {return handleImgRemove(file, fileList, 'editForm')}" list-type="picture" :limit="1"
                  :on-exceed="handleImgExceed" :auto-upload="false" :file-list="editimage">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过400kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="简介" prop="info">
                <el-input type="textarea" :rows="5" v-model="editForm.info" placeholder="请填写简介" clearable maxlength="255" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="初始采购价" prop="pur_price">
                <el-input-number v-model="editForm.pur_price" :precision="2" :step="0.1" :min="0.01"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动价" prop="act_price">
                <el-input-number v-model="editForm.act_price" :precision="2" :step="0.1" :min="0.01"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="非授信百分比" prop="ot_price_percent">
                <el-input-number v-model="editForm.ot_price_percent" :precision="0" :step="1" :min="100"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授信价百分比" prop="price_percent">
                <el-input-number v-model="editForm.price_percent" :precision="0" :step="1" :min="100"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="editForm.sort" :precision="0" :step="1" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_new">
                      <el-checkbox v-model="editForm.is_new">新品</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_hot">
                      <el-checkbox v-model="editForm.is_hot">热卖</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_good">
                      <el-checkbox v-model="editForm.is_good">优品推荐</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_activity">
                      <el-checkbox v-model="editForm.is_activity">活动</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editForm','editVisible')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editForm','editVisible')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加商品" :visible.sync="addVisible" :before-close="handleClose('addForm')" width="800px">
        <el-form ref="addForm" :model="addForm" label-width="120px" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="addForm.name" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类" prop="cate_path">
                <el-cascader clearable ref="addCascader" placeholder="请选择分类" v-model="addForm.cate_path"
                  :props="{ value: 'id',label:'name',children:'children' }" :options="cateInfo">
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="分拣中心" prop="center_id">
                <el-select v-model="addForm.center_id" placeholder="请选择分拣中心" clearable>
                  <el-option v-for="item in centerInfo" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="unit_id">
                <el-select v-model="addForm.unit_id" placeholder="请选择单位" clearable>
                  <el-option v-for="item in unitInfo" :key="item.id" :label="item.name + '---' +(item.type == 1 ? '过称' : '不过称')" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="图片" prop="image">
                <el-upload ref="addImage" name="image" action="#"
                  :on-change="(file, fileList) => {return handleImgChange(file, fileList, 'addForm', 'addImage')}"
                  :on-remove="(file, fileList) => {return handleImgRemove(file, fileList, 'addForm')}" list-type="picture" :limit="1"
                  :on-exceed="handleImgExceed" :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过400kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="简介" prop="info">
                <el-input type="textarea" :rows="5" v-model="addForm.info" placeholder="请填写简介" clearable maxlength="255" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="初始采购价" prop="pur_price">
                <el-input-number v-model="addForm.pur_price" :precision="2" :step="0.1" :min="0.01"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动价" prop="act_price">
                <el-input-number v-model="addForm.act_price" :precision="2" :step="0.1" :min="0.01"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="非授信百分比" prop="ot_price_percent">
                <el-input-number v-model="addForm.ot_price_percent" :precision="0" :step="1" :min="100"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授信价百分比" prop="price_percent">
                <el-input-number v-model="addForm.price_percent" :precision="0" :step="1" :min="100"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="addForm.sort" :precision="0" :step="1" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_new">
                      <el-checkbox v-model="addForm.is_new">新品</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_hot">
                      <el-checkbox v-model="addForm.is_hot">热卖</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_good">
                      <el-checkbox v-model="addForm.is_good">优品推荐</el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="is_activity">
                      <el-checkbox v-model="addForm.is_activity">活动</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addForm','addVisible')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addForm','addVisible')" size="small">添 加</el-button>
        </span>
      </el-dialog>
      <el-dialog title="商品详情" :visible.sync="descriptionVisible" :before-close="handleClose('descriptionForm')" width="1000px">
        <el-form ref="descriptionForm" :model="descriptionForm" label-width="100px" :rules="rules">
          <el-form-item label="详情">
            <div class="editor" id="editor" ref="editor">
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('descriptionForm','descriptionVisible')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('descriptionForm','descriptionVisible')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="记录详情" :visible.sync="logVisible" :before-close="handleClose('searchLogForm')" width="1300px">
        <el-form :inline="true" :model="searchLogForm" ref="searchLogForm">
          <el-form-item prop="status">
            <el-select v-model="searchLogForm.type" placeholder="请选择类型">
              <el-option label="采购" :value="4"></el-option>
              <el-option label="入库" :value="1"></el-option>
              <el-option label="出库" :value="2"></el-option>
              <el-option label="报损" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click.stop="searchLog(true)">搜索</el-button>
            <el-button type="success" @click.stop="searchLog">刷新</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="logTable" border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column label="类型">
            <span v-if="logType == 4" style="color:#67C23A">采购</span>
            <span v-if="logType == 1" style="color:#409EFF">入库</span>
            <span v-if="logType == 2" style="color:#E6A23C">出库</span>
            <span v-if="logType == 3" style="color:#F56C6C">报损</span>
          </el-table-column>
          <el-table-column prop="center_name" v-if="logType == 4" label="分拣中心"></el-table-column>
          <el-table-column prop="name" label="操作人姓名"></el-table-column>
          <el-table-column prop="phone" label="操作人电话"></el-table-column>
          <el-table-column prop="role_type" label="操作人角色"></el-table-column>
          <el-table-column prop="price" v-if="logType == 4" label="采购价格"></el-table-column>
          <el-table-column prop="p_weight" v-if="logType == 4" label="采购重量"></el-table-column>
          <el-table-column prop="w_weight" v-if="logType == 4" label="入库实际重量"></el-table-column>
          <el-table-column prop="equipment" v-if="logType != 4" label="设备号"></el-table-column>
          <el-table-column prop="order_id" v-if="logType == 1" label="商品采购记录表ID"></el-table-column>
          <el-table-column prop="order_id" v-if="logType == 2" label="订单ID"></el-table-column>
          <el-table-column prop="weight" v-if="logType != 4" label="重量"></el-table-column>
          <el-table-column prop="reason" label="原因"></el-table-column>
          <el-table-column prop="status" v-if="logType == 4" label="审核状态">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 1">未审核</span>
              <span v-if="scope.row.status == 2">已审核</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" v-if="logType == 4" label="过称">
            <template slot-scope="scope">
              <span v-if="scope.row.type == 1">过称</span>
              <span v-if="scope.row.type == 2">不过称</span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="(val) =>{return handleSizeChange(val,'searchLogForm', 'searchLog')}"
            @current-change="(val) =>{return handleCurrentChange(val,'searchLogForm', 'searchLog')}" :current-page="searchLogForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchLogForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="logCount">
          </el-pagination>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('searchLogForm','logVisible')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('searchLogForm','logVisible')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import E from 'wangeditor'
import md5 from 'blueimp-md5'

import {
  getGoodsOther,
  changeGoodsStatus,
  changeGoodsIsStatus,
  getGoodsList,
  getGoodsOnly,
  addGoods,
  editGoods,
  delGoods,
  getGoodsDesc,
  editGoodsDesc,
  getLogList,
  getCategorySimpleList
} from '@/network/api.js'

export default {
  name: 'goods',
  data() {
    return {
      editor: '',
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: '',
        unit_type: '',
        is_activity: '',
        cate_ids: []
      },
      table: [],
      count: 0,
      editForm: {
        id: 0,
        name: '', // 名称
        image: '', // 图片
        center_id: '', // 分拣中心ID
        unit_id: '', // 商品单位id
        cate_path: [], // 分类路径
        info: '', // 商品简介
        pur_price: 0.01, // 采购价格
        act_price: 0.01, // 活动价格
        ot_price_percent: 100, // 非授信用户价格百分比
        price_percent: 100, // 授信用户价格百分比
        sort: 1 // 排序
      },
      editimage: [], // 编辑原始image
      // 添加表单
      addForm: {
        name: '', // 名称
        image: '', // 图片
        center_id: '', // 分拣中心ID
        unit_id: '', // 商品单位id
        cate_path: [], // 分类路径
        info: '', // 商品简介
        pur_price: 0.01, // 采购价格
        act_price: 0.01, // 活动价格
        ot_price_percent: 100, // 非授信用户价格百分比
        price_percent: 100, // 授信用户价格百分比
        sort: 1, // 排序
        is_hot: false, // 是否热卖
        is_new: false, // 是否新品
        is_good: false, // 是否优品推荐
        is_activity: false // 是否活动中
      },
      descriptionForm: {
        id: 0,
        description: ''
      },
      seachrCateInfo: [], // 搜索使用的商品分类
      cateInfo: [], // 商品分类
      centerInfo: [], // 分拣中心
      unitInfo: [], // 单位
      fileList: [],
      editVisible: false, // 编辑
      addVisible: false, // 添加
      descriptionVisible: false,
      searchLogForm: {
        page: 1,
        limit: 10,
        type: 4,
        goods_id: 0
      },
      logTable: [],
      logCount: 0,
      logType: 4,
      logVisible: false,
      rules: {
        name: [{ required: true, message: '名称必须', trigger: 'blur' }],
        image: [{ required: true, message: '图片必须', trigger: 'change' }],
        info: [{ required: true, message: '简介必须', trigger: 'blur' }],
        act_price: [{ required: true, message: '活动价必须', trigger: 'change' }],
        pur_price: [{ required: true, message: '初始化采购价必须', trigger: 'change' }],
        ot_price_percent: [{ required: true, message: '非授信百分比必须', trigger: 'change' }],
        price_percent: [{ required: true, message: '授信百分比必须', trigger: 'change' }],
        cate_path: [
          { type: 'array', required: true, message: '分类必须', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.length !== 3) {
                callback(new Error('请选择第三级分类'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        center_id: [{ required: true, message: '请选择分拣中心', trigger: 'change' }],
        unit_id: [{ required: true, message: '请选择单位', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getCategorySimpleList()
    this.search()
  },
  computed: {
    unitTypeName() {
      return type => {
        switch (type) {
          case 1:
            return '过称'
          case 2:
            return '不过称'
        }
      }
    }
  },
  methods: {
    refresh() {
      this.getCategorySimpleList()
      this.search()
    },
    // 每页条数变化
    handleSizeChange(val, formName, searchName) {
      this[formName].limit = val
      this[searchName]()
    },
    // 当前页变化
    handleCurrentChange(val, formName, searchName) {
      this[formName].page = val
      this[searchName]()
    },
    // 添加文件
    handleImgChange(file, fileList, formName, uploadName) {
      if (file && file.status === 'ready') {
        // 判断文件类型
        const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
        if (imageType.indexOf(file.raw.type) === -1) {
          this.$refs[formName].fields[3].error = '请上传png|jpg|jpeg图片'
          this.$refs[uploadName].clearFiles()
          return false
        }
        if (file.size > 1024 * 400) {
          this.$refs[formName].fields[3].error = '请上传小于400kb图片'
          this.$refs[uploadName].clearFiles()
          return false
        }
        this[formName].image = file.raw
        this.$refs[formName].clearValidate('image')
      }
    },
    handleImgRemove(file, fileList, formName) {
      // console.log(file)
      // if (file && file.status === 'ready') {
      // 移除方法
      this[formName].image = ''
      this.$refs[formName].validateField('image')
      // }
    },
    // 超出上传个数
    handleImgExceed(files, fileList) {
      this.$message.error('已有image图片请先删除')
    },
    async getCategorySimpleList() {
      try {
        const rtn = await getCategorySimpleList({})
        this.seachrCateInfo = rtn
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await getGoodsList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    async add() {
      try {
        const rtn = await getGoodsOther({})
        this.addVisible = true
        this.$nextTick(() => {
          this.cateInfo = rtn.cateInfo
          this.centerInfo = rtn.centerInfo
          this.unitInfo = rtn.unitInfo
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 修改状态
    changeStatus(ev) {
      this.$confirm('您确定要修改状态吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await changeGoodsStatus({ id: ev.id, status: ev.status })
          } catch (e) {
            ev.status = ev.status === 1 ? 2 : 1
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          ev.status = ev.status === 1 ? 2 : 1
          this.$message.warning('您已取消操作')
        })
    },
    // 修改商品热卖|新品|优品推荐状态
    changeIsStatus(row, isName) {
      let msg = ''
      switch (isName) {
        case 'is_new':
          msg = '新品'
          break
        case 'is_hot':
          msg = '热卖'
          break
        case 'is_good':
          msg = '优品推荐'
          break
        case 'is_activity':
          msg = '活动'
          break
      }
      this.$confirm(`您确定要修改${msg}状态吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await changeGoodsIsStatus({ id: row.id, is_name: isName, is_status: row[isName] })
          } catch (e) {
            row[isName] = row[isName] === 1 ? 0 : 1
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          row[isName] = row[isName] === 1 ? 0 : 1
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('此操作将删除当前商品, 是否确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await delGoods({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getGoodsOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.info
          this.editForm.cate_path = rtn.info.cate_path.split(',').map(item => parseInt(item))
          this.editimage = [{ url: [rtn.info.image] }]
          this.cateInfo = rtn.cateInfo
          this.centerInfo = rtn.centerInfo
          this.unitInfo = rtn.unitInfo
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 商品详情
    async description(id) {
      try {
        const rtn = await getGoodsDesc({ id })
        this.descriptionVisible = true
        this.$nextTick(() => {
          this.editor = new E('#editor') // new即可
          this.editor.customConfig.uploadImgServer =
            process.env.NODE_ENV === 'development' ? 'http://sxb.test.com/back/goods/uploadEditorImg' : '/back/goods/uploadEditorImg'

          this.editor.customConfig.uploadImgHeaders = {
            Authorization: this.$storage.get('token')
          }
          const nonceStr = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
          let nonce = ''
          for (let index = 0; index < 6; index++) {
            nonce += nonceStr[Math.floor(Math.random() * 62)]
          }
          this.editor.customConfig.uploadImgParams = {
            nonceStr: nonce,
            sign: md5('nonceStr=' + nonce)
          }
          this.editor.customConfig.uploadFileName = 'image'
          // change事件，当富文本编辑器内容发生变化时便会触发此函数
          this.editor.customConfig.onchange = text => {
            this.descriptionForm.description = text
          }
          this.editor.customConfig.customAlert = info => {
            // info 是需要提示的内容
            this.$message.error(info)
          }
          this.editor.customConfig.uploadImgHooks = {
            before: (xhr, editor, files) => {
              if (files[0].size > 1024 * 100) {
                return {
                  prevent: true,
                  msg: '图片不能大于100kb'
                }
              }
            },
            error: (xhr, editor) => {
              this.$message.error('上传出错')
            },
            timeout: function(xhr, editor) {
              // 图片上传超时时触发
              // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            customInsert: (insertImg, result, editor) => {
              if (result.code !== 200) {
                return this.$message.error(result.msg)
              } else {
                insertImg(result.data)
                return this.$message.success(result.msg)
              }
            }
          }
          this.editor.create() // 以上配置完成之后调用其create()方法进行创建
          this.editor.txt.html(rtn.description) // 创建完成之后的默认内容
          this.descriptionForm = rtn
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 商品记录
    showLog(id) {
      this.searchLogForm.goods_id = id
      this.searchLog()
    },
    async searchLog(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchLogForm.page = 1
        }
        const rtn = await getLogList(this.searchLogForm)
        this.logTable = rtn.list
        this.logCount = rtn.count
        this.logType = rtn.log_type
        this.logVisible = true
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    handleCommand(command) {
      switch (command.cmd) {
        case 'del':
          this.del(command.id)
          break
        case 'edit':
          this.edit(command.id)
          break
        case 'description':
          this.description(command.id)
          break
        case 'showLog':
          this.showLog(command.id)
          break
      }
    },
    myClose(formName) {
      switch (formName) {
        case 'addForm':
          this.$refs.addForm.resetFields()
          this.$refs.addImage.clearFiles() // 删除预览
          break
        case 'editForm':
          this.$refs.editForm.resetFields()
          this.$refs.editImage.clearFiles() // 删除预览
          break
        case 'descriptionForm':
          this.$refs.descriptionForm.resetFields()
          break
        case 'searchLogForm':
          this.searchLogForm = {
            page: 1,
            limit: 10,
            goods_id: 0,
            type: 4
          }
          break
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.myClose(formName)
        done()
      }
    },
    // 取消按钮
    close(formName, visibleName) {
      this.myClose(formName)
      this[visibleName] = false
    },
    send(formName, visibleName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'editForm': // 编辑
              try {
                await editGoods(this.editForm)
                this.close(formName, visibleName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加
              try {
                await addGoods(this.addForm)
                this.close(formName, visibleName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'descriptionForm': // 详情
              try {
                await editGoodsDesc(this.descriptionForm)
                this.close(formName, visibleName)
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.editor {
  width: 100%;
  // height: 600px;
  // margin-bottom: 40px;
}
/deep/.w-e-text-container {
  height: 400px !important;
}
</style>
